<?php

/**
 * Framework_Module_CP_Messages
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Modules
 * @filesource
 */

/**
 * Framework_Module_CP_Messages
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @package Modules
 */
class Framework_Module_CP_Messages extends Framework_Module_CP
{

	/**
	 * $navParts
	 *
	 * @access      private
	 * @var         array		$navParts      Url parts
	 */
	private $navParts;


	/**
	 * __construct
	 *
	 * Initializes the module: sets the default presenter, the allowed
	 * conrollers, and the allowed events
	 *
	 * @access 		public
	 * @return 		void
	 */
	public function __construct()
	{
		parent::__construct();
		$this->navParts = Framework::$request->requestParts;
	}

	/**
	 * __default
	 *
	 * Launches appropriate event, such as listMessages, read, new etc
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function __default()
	{

		switch (true) {
			case (strcasecmp($this->navParts[0],'new') == 0) :
				$this->newMessage();
				break;

			case (strcasecmp($this->navParts[0],'readSent') == 0) :
				$this->readMessage(true);
				break;

			case (strcasecmp($this->navParts[0],'read') == 0) :
				$this->readMessage();
				break;

			case (strcasecmp($this->navParts[0],'reply') == 0) :
				$this->reply();
				break;
					
			case (strcasecmp($this->navParts[0],'delete') == 0 && preg_match('/^[0-9]+$/', $this->navParts[2])) :
				$this->tplFile = 'DeletedMessage.tpl';
				if($this->delete(array($this->navParts[2] => $this->navParts[2]))) {
				 $this->setData('formResponse', 'Message Deleted');
				}
				break;


					

			default:
				if ($this->navParts[0] && !$this->navParts[1])
				$this->navParts[1] = $this->navParts[0];
				$this->navParts[0] = 'list';
				$this->listMessages();
				break;
		}
	}

	/**
	 * listMessages
	 *
	 *
	 * @access 		public
	 * @return 		void
	 */
	public function listMessages()
	{
		// Template
		$this->tplFile = 'ListMessages.tpl';

		// Navigator
		$navigator = new Framework_Navigator('/'.Framework::$request->ownerName.'/CP/Messages/list/','messageNavigator');
		$navigator->setItem('allItem','all','From All');
		$navigator->setItem('friendsItem','friends','From Friends');
		$navigator->setItem('watchingItem','watching','From Watching');
		$navigator->setItem('watchedyByItem','watchedBy','From Watched By');
		$navigator->setItem('otherItem','other','Other');
		$navigator->setItem('sentItem','sent','View Sent');



		// Perspective
		$perspective[0] = 'Sen';
		$perspective[1] = 'Rec';
		$perspective[2] = 'recieverStatus';

		// Join conditions
		switch (true) {
			case (strcasecmp($this->navParts[1],'friends') == 0):
				$join = 'AND MsgCategory.val = "friends"';
				$navigator->setActive('friendsItem');
				break;

			case (strcasecmp($this->navParts[1],'watching') == 0):
				$join = 'AND MsgCategory.val = "watching"';
				$navigator->setActive('watchingItem');
				break;

			case (strcasecmp($this->navParts[1],'watchedBy') == 0):
				$join = 'AND MsgCategory.val = "watchedBy"';
				$navigator->setActive('watchedByItem');
				break;

			case (strcasecmp($this->navParts[1],'other') == 0):
				$join = 'AND MsgCategory.val = "other"';
				$navigator->setActive('otherItem');
				break;

			case (strcasecmp($this->navParts[1],'sent') == 0):
				$join = '';
				$perspective[0] = 'Rec';
				$perspective[1] = 'Sen';
				$perspective[2] = 'senderStatus';
				$navigator->setActive('sentItem');
				$this->setData('sent','Sent');
				break;

			default:
				$join = '';
				$this->navParts[1] = 'all';
				$navigator->setActive('allItem');
				break;
		}

		$this->setData('msgNav',$navigator->getNavigation());

		$this->forms['form'] = Framework_Quickform::factory('form', 'post', '/'.$this->owner->userName.'/CP/Messages/'.$this->navParts[0].'/'.$this->navParts[1]);

		// Process form
		if ($this->forms['form']->validate()) {
			$result =$this->forms['form']->process(array($this, 'delete'));

			if (!PEAR::isError($result)) {
				$this->setData('formResponse','Message(s) Deleted');
			} else {
				$this->setData('formResponse','Error: Messages could not be deleted');
			}
		}


		$messageDB = Framework_DB::dbFactory('Message');

		$filter = 'PrivateMsg.idSiteUser'.$perspective[0].' = SiteUser.idSiteUser
		           AND PrivateMsg.idSiteUser'.$perspective[1].' = '.$this->owner->idSiteUser.' 
				   AND PrivateMsg.'.$perspective[2].' = 1 '.$join;

		$queryArray = array(
		'sqlKey' => 'getMessages',
		'filter' => $filter
		);

		$dataGrid = Framework_DB::dataGridFactory($messageDB, $queryArray, 20);

		if (PEAR::isError($dataGrid)) {
			return $dataGrid;
		}

		$messages = $dataGrid->getData();

		if (!PEAR::isError($messages) && count($messages)) {
				
			$this->setData('messages',$messages);
			$this->setData('pager',$dataGrid->getPager());
			foreach ($messages as $message) {
				$this->forms['form']->addElement('checkbox',$message['idPrivateMsg']);
			}
			$this->forms['form']->addElement('submit','btnSubmit','Delete Selected','class="button" id="btnSubmit"');
				
		} else {
			$this->setData('noResults','No messages to list');
		}




	}


	/**
	 * delete
	 *
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function delete($inputArray)
	{

		if (strcasecmp($this->navParts[1],'sent') == 0) {
			$field[0] = 'senderStatus';
			$field[1] = 'Sen';
		} else {
			$field[0] = 'recieverStatus';
			$field[1] = 'Rec';
		}

		foreach ($inputArray AS $key=>$value) {
			if (preg_match('/^[0-9]+$/', $key)){
				$ids[] = $key;
			}
		}

		$in = '('.implode(',',$ids).')';

		$where = 'idSiteUser'.$field[1].' = '.$this->owner->idSiteUser.' AND idPrivateMsg IN'.$in;

		$messageDB = Framework_DB::dbFactory('Message');

		$data = array($field[0] => 0);

		$result = $messageDB->update('PrivateMsg', $data, $where);

		if (PEAR::isError($result)) {
			return $result;
		}

		//		$sql = 'UPDATE privatemessage SET '.$field[0].' = 0 WHERE idSiteUser_'.$field[1].' = '.$this->owner->idSiteUser.'
		//			    AND idPrivateMessage IN'.$in;
		//		$result = $this->db->query($sql);

		// Prune
		// Note: Need to add logic to make this similar to session/cache handling
		$where = 'senderStatus = 0 AND recieverStatus = 0';

		$result = $messageDB->delete('PrivateMsg', $where);


		//		$sql2 = 'DELETE FROM privatemessage WHERE senderStatus = 0 AND recieverStatus = 0';
		//		$result2 = $this->db->query($sql);

		if (PEAR::isError($result)) {
			return $result;
		} else {
			return true;
		}
	}

	/**
	 * reply
	 *
	 *
	 * @access 		public
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function reply()
	{
		// Evaluate id
		if ($this->navParts[1] && preg_match('/^[0-9]+$/',$this->navParts[1])) {
			return $this->newMessage($this->navParts[1]);
		}
	}

	/**
	 * readMessage
	 *
	 *
	 * @access 		public
	 * @param 		boolean		$readSent		Whether or not to get a send message
	 * @return 		void
	 */
	public function readMessage($readSent = false)
	{
		if(Framework::$request->isAjax()) {
			$this->presenter = 'Module';
		}

		$messageDB = Framework_DB::dbFactory('Message');

		//name/CP/Messages/readSent/
		if ($readSent) {
			//			$field[0] = 'Reciever';
			//			$field[1] = 'Sender';
			$query = 'getSentMessage';
			$this->setData('deleteFromOption','sent');
		} else {
			//			$field[0] = 'Sender';
			//			$field[1] = 'Reciever';
			$query = 'getMessage';
			$this->setData('deleteFromOption','all');

		}

		// Set Template
		$this->tplFile = 'ReadMessage.tpl';

		// Evaluate id
		if ($this->navParts[1] && preg_match('/^[0-9]+$/',$this->navParts[1])) {
			$messageID = $this->navParts[1];
			$queryArray = array(
			'sqlKey' => $query,
			'params' => array($messageID, $this->owner->idSiteUser)
			);
				
			$messageDB = Framework_DB::dbFactory('Message');
				
			$message = $messageDB->select($queryArray);
			if (!PEAR::isError($message)) {
				if (is_array($message)) {
					// Update read status
					$result = $messageDB->update('PrivateMsg', array('readStatus' => 1), array('idPrivateMsg' => $message['idPrivateMsg'], 'idSiteUserRec' => $this->owner->idSiteUser));
						

					if (PEAR::isError($result)) {
						$errors[] = $result->getMessage();
					}

					$this->setData('message',$message);
				} else {
					$errors[] = 'No Message Found';
				}
			} else
			$errors[] = $message->getMessage();

		} else {
			$errors[] = 'Invalid ID';
		}

		if ($errors)
		$this->setData('errors',$errors);

		return true;

	}

	/**
	 * newMessage
	 *
	 *
	 * @access 		public
	 * @param 		int			$responseTo		Message id to respond to
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function newMessage($responseTo = null)
	{
		if(Framework::$request->isAjax()) {
			$this->presenter = 'Module';
		}

		$this->tplFile = 'NewMessage.tpl';


			
		$queryArray = array(
		'sqlKey' => 'getPeople',
		'params' => array($this->owner->idOwner, 1, 1)
		);


		$this->forms['newMessage'] = Framework_Quickform::factory('newMessage', 'post', Framework::$request->getBaseHTTPPath().'/'.$this->owner->userName.'/CP/Messages/new');
		$this->forms['newMessage']->addElement('text','title','Title: ', 'size="40" class="textInput" id="title"');
		$this->forms['newMessage']->addElement('text','to','To: ', 'size="40" class="textInput" id="to"');
		if ($this->owner->selectCount($queryArray) && !$responseTo) {
			$queryArray = array(
			'sqlKey' => 'getPeopleList',
			'params' => array($this->owner->idOwner, 1, 1)
			);
				
			$result = $this->owner->select($queryArray);
				
			if(PEAR::isError($result)) {
				return $result;
			}
				
			if (!PEAR::isError($result) && count($result)) {
				$friendsList = array(""=>"Choose Friend") + $result;
				$this->forms['newMessage']->addElement('select', 'friendsList', 'Choose Friend: ', $friendsList, 'class="listInput" id="friendsList"');
			}
		}
		$this->forms['newMessage']->addElement('textarea','message','Message: ','class="textInput" id="message"');
		$this->forms['newMessage']->addElement('submit','btnSubmit','Send','class="button" id="btnSubmit" ');

		// Defaults
		if (isset($_GET['to'])) {
			$queryArray = array(
			'sqlKey' => array(
			'select' => 'userName, siteDomain',
			'from'   => 'SiteUser',
			'where'  => 'idSiteUser = ?',
			'get'	 => 'row'
				),
			'params' => array($_GET['to']),
			'count'  => 1
			);
				
			$result = $this->owner->select($queryArray);
			if (count($result) && !PEAR::isError($result)) {
				$this->forms['newMessage']->setDefaults(array('to'=>($result['userName'].'@'.$result['siteDomain'])));
			}
		}

		// Response
		if ($responseTo) {
				
			$queryArray = array(
			'sqlKey' => 'getMessage',
			'params' => array($responseTo, $this->owner->idSiteUser)
			);
				
			$messageDB = Framework_DB::dbFactory('Message');
				
			$message = $messageDB->select($queryArray);

			if(is_array($message) && !PEAR::isError($message)) {
				$this->forms['newMessage']->setDefaults(array('title'  =>'RE: '.$message['messageTitle'],
				'to'     =>$message['userName'].'@'.$message['siteDomain'],
				'message'=>$message['message']));
			} else {
				return $message;
			}
		}

		// Filters
		$this->forms['newMessage']->applyFilter('__ALL__','trim');
		$this->forms['newMessage']->applyFilter('__ALL__','htmlentities');

		// Requirements

		// Process form
		if ($this->forms['newMessage']->validate()) {
			$result = $this->forms['newMessage']->process(array($this, 'processNewMessage'));
			if (PEAR::isError($result)) {
				$errors[] = $result->getMessage();
				$this->setData('errors',$errors);
				return true;
			} else {
				$this->setData('formResponse','Message Sent');
			}
		} else {
			return true;
		}
		return $result;
	}

	/**
	 * processNewMessage
	 *
	 *
	 * @access 		public
	 * @param 		array		$data		Data to process
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function processNewMessage($data)
	{
		$message = new Framework_Message($this->owner);
		if (strlen($data['friendsList'])) {
			$message->setTo($data['friendsList']);
		} else {
			$message->setTo($data['to']);
		}

		$message->setTitle($data['title']);
		$message->setMessage($data['message']);
		$result = $message->send();
		if (PEAR::isError($result)) {
			return $result;
		} else {
			return true;
		}
	}



}

?>